#include "Common.fxh"

Texture2D gDepthTex;
Texture2D gNormal_SpecP_Tex;
Texture2D gDiffuse_SpecI_Tex;
Texture2D gSpecP_Tex;

SamplerState gPointSam
{
	Filter = MIN_MAG_MIP_POINT;
	AddressU = Wrap;
	AddressV = Wrap;
};

//return float4(pIn.posD.z * 0.4f, 0, 0, 1);
//float swz = pIn.posH.z;

//if(fcmp(swz, pIn.posD.z)) return float4(1,1,0,1);
//else return float4(1,0,0,1);

//float2 hw = pIn.posD.xy / float2(1024, 600);
//float2 sw = pIn.posH.xy * float2(0.5f, -0.5f) + float2(0.5f, 0.5f);
//if(fcmp(sw.x, hw.x) && fcmp(sw.y, hw.y)) return float4(1,1,0,1);
//else return float4(1,0,0,1);

void getPixelParamsFromGBuffer(in float2 texCoord, out float3 normalV, out float3 diffColor, out float specIntens, out float specPower)
{
	float4 diffAndSpecIntens = gDiffuse_SpecI_Tex.Sample(gPointSam, texCoord);
	diffColor = diffAndSpecIntens.xyz;
	specIntens = diffAndSpecIntens.w;
	
	float4 specPowerRT = gSpecP_Tex.Sample(gPointSam, texCoord);
	specPower = decodeSpecPowerFromUNorm(specPowerRT.x);
	
	//float2 normalXY = gNormal_SpecP_Tex.Sample(gLinearSam, texCoord).xy;
	//float3 normalV = float3(normalXY.xy, -sqrt(1.0f - normalXY.x * normalXY.x - normalXY.y * normalXY.y));

	normalV = float3(gNormal_SpecP_Tex.Sample(gPointSam, texCoord).xy, specPowerRT.y);
}

void getPixelParamsFromGBufferLoad(in int3 texCoord, out float3 normalV, out float3 diffColor, out float specIntens, out float specPower)
{
	float4 diffAndSpecIntens = gDiffuse_SpecI_Tex.Load(texCoord);
	diffColor = diffAndSpecIntens.xyz;
	specIntens = diffAndSpecIntens.w;
	
	float4 specPowerRT = gSpecP_Tex.Load(texCoord);
	specPower = decodeSpecPowerFromUNorm(specPowerRT.x);
	
	//float2 normalXY = gNormal_SpecP_Tex.Sample(gLinearSam, texCoord).xy;
	//float3 normalV = float3(normalXY.xy, -sqrt(1.0f - normalXY.x * normalXY.x - normalXY.y * normalXY.y));

	normalV = float3(gNormal_SpecP_Tex.Load(texCoord).xy, specPowerRT.y);
}

float3 calculateLighting(in float3 viewRayV, in float3 lightDirV, in float3 normalV, in float4 gLightColorAndIntens,
						in float3 diffColor, in float specIntens, in float specPower)
{
	float3 diffuse = saturate(dot(normalV, lightDirV)) * diffColor;

	float3 lightDirReflV = reflect(lightDirV, normalV);
	float specular = pow( saturate(dot(viewRayV, lightDirReflV)), specPower ) * specIntens;

	return gLightColorAndIntens.w * gLightColorAndIntens.xyz * (diffuse + specular.xxx);
}